<?php
namespace app\plus\controller;

use app\common\model\ShopOrderModel;
use app\common\model\ShopPaymentModel;
use app\common\model\ShopPromotionAuctionLogModel;
use app\common\model\ShopCardModel;
use app\common\model\ShopCardOrderModel;
use app\common\model\ShopPromotionGroupbuyCartModel;
use Payment\ChargeContext;
use Payment\Config;
use Payment\NotifyContext;
use think\Controller;
use think\helper\Str;

class AlipayController extends Controller
{

    //获取支付宝配置参数
    private function getAliConfig($siteId)
    {
        $paymentModel = new ShopPaymentModel();
        $payInfo      = $paymentModel->where('site_id', $siteId)->where('pay_code', 'alipay')->find();
        $aliconfig    = $payInfo->pay_config;
        if (empty($aliconfig['rsa_private_key'])) { //采用MD5验签
            $aliconfig['sign_type'] = 'MD5';
        }
        $notifyConfig = $this->setNotify($siteId);
        $aliconfig    = array_merge($aliconfig, $notifyConfig);
        return $aliconfig;
    }

    /**
     * 阿里支付
     */
    public function pay()
    {
        $siteId              = $this->request->param('site_id');
        $orderType              = $this->request->param('order_type');
        $orderSn                = $this->request->param('order_sn');
        $aliconfig              = $this->getAliConfig($siteId);
        $payData                = $this->getOrder($orderType, $orderSn);
        $payData['client_ip']   = get_client_ip();
        if (empty($payData)) {
            $this->error('参数错误！');
        }
        $charge = new ChargeContext();
        try {
            $charge->initCharge(Config::ALI_CHANNEL_WEB, $aliconfig);
            $url = $charge->charge($payData);
        } catch (PayException $e) {
            echo $e->errorMessage();
            exit;
        }
        $this->redirect($url);
    }

    /**
     * 获取订单信息
     * @param $orderType
     * @param $orderId
     * PS:必须提供 order_no、amount、subject、body、client_ip
     */
    private function getOrder($orderType, $orderSn)
    {
        $payData = [];
        switch ($orderType) {
            case 'groupbuy_cart': //保证金详情
                $groupbuyCartModel = new ShopPromotionGroupbuyCartModel();
                $order             = $groupbuyCartModel->where('order_sn', $orderSn)->find();
                $payData           = ['order_no' => $order['order_sn'], 'amount' => $order['margin'], 'subject' => $order['order_sn'] . '缴纳保证金', 'body' => $order['goods_name'], 'extra_param'=>'groupbuy_cart'];
                break;
            case 'order': //订单详情
                $orderModel = new ShopOrderModel();
                $order      = $orderModel->where('order_sn', $orderSn)->find();
                $payData           = ['order_no' => $order['order_sn'], 'amount' => $order['order_price'], 'subject' => $order['order_sn'] . '订单支付', 'body' => $order['order_sn'] . '订单支付', 'extra_param'=>'order'];
                break;
            case 'auction': //保证金详情
                $auctionModel = new ShopPromotionAuctionLogModel();
                $order             = $auctionModel->where('pay_sn', $orderSn)->find();
                $payData           = ['order_no' => $order['pay_sn'], 'amount' => $order['money'], 'subject' => $order['pay_sn'] . '缴纳竞拍保障金', 'body' => $order['goods_name'], 'extra_param'=>'auction'];
                break;
            case 'card': //优惠券支付
                $auctionModel = new ShopCardOrderModel();
                $order             = $auctionModel->where('order_sn', $orderSn)->find();
                $payData           = [
                    'order_no' => $order['order_sn'],
                    'amount' => $order['order_price'],
                    'subject' => $order['order_sn'] . '购买优惠券',
                    'body' => $order['card_name'],
                    'extra_param'=>'card',
                    'time_expire'=>$order['end_time']
                ];
                break;
        }
        return $payData;
    }

    /**
     * 设置回调地址
     * @param $orderType
     */
    private function setNotify($siteId)
    {
        $config['notify_url'] = $this->request->domain() . '/plus/alipay/notify/site_id/'.$siteId.'.html';
        $config['return_url'] = url('home/Order/index','',true,true);
        return $config;
    }

    /**
     * 回调地址
     */
    public function notify()
    {
        $siteId = $this->request->param('site_id');
        $notify    = new NotifyContext();
        $callback  = new \app\plus\notify\PayNotify();
        $aliconfig = $this->getAliConfig($siteId);
        // 支付宝回调
        $notify->initNotify(Config::ALI, $aliconfig);
        $notify->notify($callback);
    }


}